﻿using System;
using MvcMall.Core.Commands;
using MvcMall.Framework.Extensions;
using MvcMall.Core.Contacts.Tasks;
using MvcMall.Framework.UnitOfWork;

namespace MvcMall.AdminWeb.Manage.AdminUsers
{
    public partial class Save : ManageBasePage
    {
        private IAdminRoleTask _adminRoleTask;
        private IAdminUserTask _adminUserTaks;

        protected void Page_Load(object sender, EventArgs e)
        {
            ValidatePagePower("SaveAdminUser");
            _adminRoleTask = GetInstance<IAdminRoleTask>();
            _adminUserTaks = GetInstance<IAdminUserTask>();

            if (!IsPostBack)
            {
                ddlRoles.DataSource = _adminRoleTask.GetAll().ToSelectList(m => m.Id.ToString(), m => m.RoleName);
                ddlRoles.DataBind();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var userName = txtUserName.Text.Trim();
            var password = txtPassword.Text;
            var email = txtEmail.Text.ToLower();
            var mobile = txtMobile.Text;

            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                ShowMsg("输入不完整");
                return;
            }

            var adminUser = _adminUserTaks.GetUser(userName.Trim().ToLower());
            if (adminUser != null)
            {
                ShowMsg("该管理员用户名已存在");
                return;
            }

            var cmd = new CreateAdminUserCommand
                          {
                              Email = email,
                              Mobile = mobile,
                              Password = password,
                              UserName = userName,
                              RoleId = Convert.ToInt32(ddlRoles.SelectedValue)
                          };
            using (var work = UnitOfWork.Begin())
            {
                if (_adminUserTaks.Create(cmd) != null)
                {
                    work.Commit();
                    ShowMsg("新增管理员成功", "Index.aspx");
                }
                else
                {
                    ShowMsg("新增管理员失败");
                }
            }
        }
    }
}